﻿using PetkaWebDav.Server.Framework.BaseClasses;
using PetkaWebDav.Server.Framework.Classes;
using PetkaWebDav.Server.Framework.Collections;
using PetkaWebDav.Server.Framework.Enums;
using PetkaWebDav.Server.Framework.Resources;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PetkaWebDav.Handler.FileSystem.Handlers
{
    /// <summary>
    /// Custom implementation example for DavHead.
    /// </summary>
    public sealed class DavHead : DavHeadBase
    {
        public DavHead()
        {
            this.ProcessDavRequest += new DavProcessEventHandler(DavHead_ProcessDavRequest);
        }

        private void DavHead_ProcessDavRequest(object sender, EventArgs e)
        {
            if (!RequestWrapper.ValidResourceByPath(base.RelativeRequestPath))
                base.AbortRequest(ServerResponseCode.NotFound);
            else
            {
                FileInfo _fileInfo = RequestWrapper.GetFile(base.RelativeRequestPath);

                if (_fileInfo != null)
                {
                    //TODO: handle versions

                    DavFile _davFile = new DavFile(_fileInfo.Name, _fileInfo.FullName);
                    _davFile.CreationDate = _fileInfo.CreationTime;
                    _davFile.LastModified = _fileInfo.LastWriteTime.ToUniversalTime();

                    //Check to see if there are any locks on the resource
                    //DavLockProperty _lockInfo = RequestWrapper.GetLockInfo(_fileInfo.Name);
                    DavLockProperty _lockInfo = RequestWrapper.GetLockInfo(_fileInfo);
                    if (_lockInfo != null)
                        _davFile.ActiveLocks.Add(_lockInfo);

                    //Check to see if there are any custom properties on the resource
                    DavPropertyCollection _customProperties = RequestWrapper.GetCustomPropertyInfo(_fileInfo.FullName);
                    if (_customProperties != null)
                        _davFile.CustomProperties.Copy(_customProperties);

                    _davFile.SupportsExclusiveLock = true;
                    _davFile.SupportsSharedLock = true;
                    _davFile.ContentLength = (int)_fileInfo.Length;

                    //Set the resource
                    base.Resource = _davFile;
                }
            }
        }
    }
}
